package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.UserCardMapper;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.OrderCodeFactory;
import com.wsd.smartcarwasher.util.PageInfo;
import com.wsd.smartcarwasher.util.ReturnUtil;

import com.wsd.smartcarwasher.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "(新增)会员卡-运营端卡面管理")
@Controller
@CrossOrigin
public class CardController {
    private static final Logger logger = LoggerFactory.getLogger(CardController.class);

    @Resource
    private CardService cardService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private WxService wxService;

    @Resource
    private CardRecordService  cardRecordService;

    @Resource
    private OrderService orderService;
    @Resource
    private RefundRecordService refundRecordService;
    @Resource
    private CardOrderService cardOrderService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TimeTaskService timeTaskService;
    @Resource
    private UserCardMapper userCardMapper;
    @Resource
    private WxPayService wxPayService;

    /**
     * 查询所有会员卡信息
     *
     * @return 会员卡信息（携带适用门店信息）
     */
    @ApiOperation(value="获取所有会员卡", notes = "运营端卡面管理", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/all_cards", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryAllCards() {
        return ReturnUtil.Success(ResultState.QUERY_ALL_CARDS_SUCCESS.getMsg(), cardService.queryAllCard());
    }

    /**
     * 小程序查询会员卡信息
     *
     * @return 会员卡信息（携带适用门店信息）
     */
    @ApiOperation(value="小程序查询会员卡详情", notes = "小程序查询会员卡信息", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "cardId", value = "会员卡id", required = true, dataType = "Card")
    @RequestMapping(value = "/v1/my_cards_info", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryMyCards(Integer cardId) {
        if(cardId==null)
        {
            return ReturnUtil.Error("缺少参数cardId");
        }
//        String sessionId = request.getHeader(Global.AUTHORIZATION);
//        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
//        if (user == null) {
//            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
//        }
        return ReturnUtil.Success("查询成功", cardService.queryCardByCardId(cardId));
    }

    /**
     * 查询所有会员卡信息
     *
     * @return 会员卡信息（携带适用门店信息）
     */
    @ApiOperation(value="获取所有会员卡", notes = "运营端卡面管理", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/all_cards_pc", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryAllCardsPc(@RequestParam Integer Page,@RequestParam Integer PageSize) {

        return ReturnUtil.Success(ResultState.QUERY_ALL_CARDS_SUCCESS.getMsg(),new PageInfo<>(cardService.queryAllCardPc(Page,PageSize)));
    }


    /**
     * 新增会员卡
     *
     * @param card 会员卡信息
     * @return 成功返回会员卡信息，失败返回失败状态
     */
    @Log("修建了会员卡")
    @RequiresPermissions("cards:add:new")
    @ApiOperation(value="新建会员卡", notes = "运营端卡面管理", produces = "application/json", response = Card.class)
    @ApiImplicitParam(name = "card", value = "会员卡信息", required = true, dataType = "Card")
    @RequestMapping(value = "/v1/card", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap addCard(@RequestBody @ApiParam Card card) {
        if (card == null) {
            return ReturnUtil.Error(ResultState.CARD_IS_NULL.getMsg());
        }
        int result = cardService.addCard(card);
        if (result == 0) {
            return ReturnUtil.Error(ResultState.ADD_CARD_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_CARD_SUCCESS.getMsg(), card);
    }

    /**
     * 根据id删除会员卡
     *
     * @param id 会员卡id
     * @return 返回删除结果
     */
    @Log("删除了会员卡")
    @RequiresPermissions("cards:delete")
    @ApiOperation(value="删除会员卡", notes = "运营端卡面管理", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "id", value = "会员卡id", required = true, dataType = "Integer")
    @RequestMapping(value = "/v1/delete_card", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap deleteCard(@RequestParam Integer id) {
        if (id == null || id < 1) {
            return ReturnUtil.Error(ResultState.ILLEGAL_PARAM.getMsg());
        }
        int result = cardService.deleteCard(id);
        if (result == 0) {
            return ReturnUtil.Error(ResultState.DELETE_CARD_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.DELETE_CARD_SUCCESS.getMsg());
    }

    /**
     * 更新会员卡信息
     *
     * @param card 会员卡
     * @return 返回更新结果
     */
    @Log("更新会员卡信息")
    @RequiresPermissions("cards:update")
    @ApiOperation(value="更新会员卡信息", notes = "运营端卡面管理", produces = "application/json", response = ModelMap.class)
    @ApiImplicitParam(name = "card", value = "会员卡信息", required = true, dataType = "Card")
    @RequestMapping(value = "/v1/update_card", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap updateCard(@RequestBody Card card) {
        if (card == null) {
            return ReturnUtil.Error(ResultState.CARD_IS_NULL.getMsg());
        }
        int result = cardService.updateCard(card);
        if (result == 0) {
            return ReturnUtil.Error(ResultState.UPDATE_CARD_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.UPDATE_CARD_SUCCESS.getMsg());
    }

    /**
     * 查询用户的会员卡信息
     *
     * @return 用户会员卡信息
     */
    @ApiOperation(value="用户会员卡信息", notes = "小程序端用户会员卡信息", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/user_cards", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryUserCards(HttpServletRequest request) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        return ReturnUtil.Success(ResultState.QUERY_USER_CARDS_SUCCESS.getMsg(), cardService.queryUserCards(user.getUserId()));
    }


    /**
     * 会员卡退款
     *
     * @return 会员卡退款信息
     */
    @ApiOperation(value="新增=>会员卡退款", notes = "小程序端提交会员卡退款信息", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/refund_cards", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap refundCards(HttpServletRequest request,String ucId) throws Exception {
//        logger.info("调用退款接口"+System.currentTimeMillis());
//        String sessionId = request.getHeader(Global.AUTHORIZATION);
//        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
////        UserInfo user = userInfoService.findByMobile("17791961563");
//        if (user == null) {
//            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
//        }
//        //会员卡购买记录表
//        CardRecord cardRecord =this.cardRecordService.getCardRecordInfo(ucId);
//        UserCardExample example=new UserCardExample();
//        example.createCriteria().andUcIdEqualTo(ucId);
//        List<UserCard> userCard=this.userCardMapper.selectByExample(example);
//
//       if(userCard.isEmpty())
//       {
//          if(cardRecord.getUserId().equals(user.getUserId()))
//          {
//              return ReturnUtil.Error("代付会员卡退款请从会员卡持有用户入口退款！");
//          }
//           return ReturnUtil.Error(ResultState.QUERY_USER_CARDS_ERROR.getMsg());
//       }
//        if(cardRecord==null&&!userCard.isEmpty())
//        {
//            return ReturnUtil.Error(ResultState.QUERY_USER_REFUNDED_ERROR.getMsg());
//        }
//        Date vailDate = DateUtils.addDays(cardRecord.getPayTimes(), 30);
//        if(System.currentTimeMillis()>vailDate.getTime())
//        {
//            return ReturnUtil.Error(ResultState.REFUND_CARD_DAY_DISMATCH.getMsg());
//        }
//        if(cardRecord.getFirstTimes()!=null)
//        {
//            return ReturnUtil.Error(ResultState.REFUND_CARD_USE_DISMATCH.getMsg());
//        }
//        if(cardRecord.getRefundTime()!=null)
//        {
//            return ReturnUtil.Error(ResultState.REFUND_CARD_DISMATCH.getMsg());
//        }
//        if(Long.valueOf(userCard.get(0).getValidDate().getTime())<Long.valueOf(new Date().getTime()))
//        {
//            return ReturnUtil.Error(ResultState.REFUND_CARD_EXPIRE.getMsg());
//        }
//        String partner_trade_no = OrderCodeFactory.getOrderCode(cardRecord.getCardId().longValue());
//        CardOrder cardOrder=this.cardOrderService.queryOrderInfoByUcId(ucId);
//        if(!StringUtil.isNullOrEmpty(this.refundRecordService.hascheckUserExistRefundApply(cardOrder.getOrderSn())))
//        {
//            return ReturnUtil.Error(ResultState.REFUND_CARD_EXIST.getMsg());
//        }
//        int price =  cardOrder.getPayPrice().movePointRight(2).intValue();
//        if(cardOrder.getIsHepaid()==1)
//        {
//            user=this.userInfoService.findById(cardOrder.getHeuserId());
//        }
//        TRefundRecord tRefundRecord=this.refundRecordService.checkUserExistRefundApply(cardOrder.getOrderSn());
//        if(StringUtil.isNullOrEmpty(tRefundRecord))
//        {
//           this.refundRecordService.userApplyRefund(cardOrder.getOrderSn());
//        }
//        return  this.wxPayService.refundByWx(cardOrder);
        return ReturnUtil.Error("退款功能正在努力优化中,敬请期待");
    }



    /**
     * 查询用户的会员卡信息
     *
     * @return 用户会员卡信息
     */
    @ApiOperation(value="pc端-用户会员卡信息", notes = "pc端-用户会员卡信息", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/pc/user_cards", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap queryUserCards(@RequestParam String userId) {

        return ReturnUtil.Success(ResultState.QUERY_USER_CARDS_SUCCESS.getMsg(), cardService.queryUserCards(userId));
    }







    /**
     * 查询用户的会员卡信息
     *
     * @return 用户会员卡信息
     */
    @ApiOperation(value="小程序端删除用户会员卡信息", notes = "小程序端删除用户会员卡信息", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/deleteUserCard", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap deleteUserCard(HttpServletRequest request,@RequestParam String ucId) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        int rows = this.cardService.deleteUserCard(user.getUserId(),ucId);
        if(rows>0){

            return ReturnUtil.Success("删除成功");
        }
        return ReturnUtil.Error("删除失败");
    }

}
